package com.nhncorp.pleiades.demo;

import java.io.File;
import java.util.Iterator;

import org.jgroups.blocks.ReplicatedTree;

public class ReplicaFileSystem {

  public static void main(String args[]) {
    ReplicatedTree tree;
    String start_directory = null;
    boolean jmx = false;

    String props = "udp.xml";

    for (int i = 0; i < args.length; i++) {
      if ("-props".equals(args[i])) {
        props = args[++i];
        continue;
      }
      if ("-start_directory".equals(args[i])) {
        start_directory = args[++i];
        continue;
      }
      if ("-jmx".equals(args[i])) {
        jmx = true;
        continue;
      }
      help();
      return;
    }

    try {
      tree = new ReplicatedTree("ReplicatedTreeDemo-Group", props, 10000, jmx);

      System.out.println("starting ...");
      if (start_directory != null && start_directory.length() > 0) {
        
        populateTree(tree, start_directory);
      } else {
        start_directory = ".";
        populateTree(tree, start_directory);
        /*
         * HashMap map=new HashMap(); map.put("name", "Framework");
         * map.put("pid", new Integer(322649));
         * tree.put("/federations/fed1/servers/Framework", map);
         * tree.put("/federations/fed1/servers/Security", null);
         * tree.put("/federations/fed1/servers/Security/components/RuntimeMonitor",
         * null); tree.put("/federations/fed1/servers/fenics", null);
         */
      }
      
      Iterator it = tree.getChildrenNames(".").iterator();
      while(it.hasNext()) {
        System.out.println(it.next());
      }
      System.out.println("done ...");
      tree.stop();
    } catch (Exception ex) {
      ex.printStackTrace(System.err);
    }
  }

  static void help() {
    System.out.println("ReplicatedTreeView [-help] "
        + "[-props <channel properties>] [-start_directory <dirname>] [-jmx]");
  }

  static void populateTree(ReplicatedTree tree, String dir) {
    File file = new File(dir);

    if (!file.exists())
      return;
    tree.put(dir, null);

    if (file.isDirectory()) {
      String[] children = file.list();
      if (children != null && children.length > 0) {
        for (int i = 0; i < children.length; i++)
          populateTree(tree, dir + '/' + children[i]);
      }
    }
  }
}
